const {
  MemberModel
} = require('../../../utils/member-model.js');
var wxcode =
  require('../../../utils/index.js');
var memberModel = new MemberModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponName: "", //兑换券名称
    couponCode: "", //兑换券静态码
    validEnd: "", //有效期结束时间
    qrCode: "",
    isQrCode: false, //是否显示动态码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      couponName: options.name != "null" ? options.name : '' || '',
      couponCode: options.code != "null" ? options.code : '' || '',
      validEnd: options.time || '',
    }, function () {
      if (this.data.couponCode != "null" && this.data.couponCode != "") {
        this.getCodeQuery(this.data.couponCode);
      } else {
        wx.showToast({
          title: `电子码不能为空`,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  /**
   * 电子码查询
   * */
  getCodeQuery: function (code) {
    var param = {
      electron_code: code,
      merchantId: wx.getStorageSync('merchantId')
    }
    memberModel.codeQuery(param).then(data => {
      /*如果是动态验证码*/
      if (data.is_dynamic == 1) {
        this.setData({
          qrCode: "XXX XXX XXX"
        })
      } else {
        this.setData({
          qrCode: code.replace(/\s/g, '').replace(/(\d{3})(?=\d)/g, "$1 "),
          isQrCode: true
        }, function () {
          this.createQrCode(code);
        })
      }
    }).catch(err => {
      if (err.code == "1000") {
        this.setData({
          qrCode: "XXX XXX XXX"
        })
      } else {
        this.setData({
          qrCode: code.replace(/\s/g, '').replace(/(\d{3})(?=\d)/g, "$1 "),
          isQrCode: true
        }, function () {
          this.createQrCode(code);
        })
      }
    })
  },
  /**
   * 获取兑换码
   */
  getRedeemCode: function () {
    var param = {
      electron_code: this.data.couponCode,
      merchantId: wx.getStorageSync('merchantId')
    }
    memberModel.codeDynamic(param).then(data => {
      this.setData({
        qrCode: data.dynamic_code.replace(/\s/g, '').replace(/(\d{3})(?=\d)/g, "$1 "),
        isQrCode: true
      }, function () {
        this.createQrCode(data.dynamic_code);
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.message}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 设置二维码
   */
  createQrCode: function (qr_code) {
    wxcode.qrcode(qr_code, "myQrcode", 300, 300)
  },
})